<script setup lang="ts">
  import { getCodeAPI, loginByMobileApi } from '@/api/user'
  import useUserStore from '@/stores/user'
  import { ref } from 'vue'
  // 表单数据
  const formData = ref({
    mobile: '13230000003',
    code: '',
  })

  defineOptions({
    options: {
      styleIsolation: 'shared',
    },
  })
  const showCountDown = ref(false)

  const onShowCountDown = async () => {
    try {
      await formRef.value!.validateField!(['mobile'])
    } catch (error) {
      uni.showToast({
        title: '请输入正确的手机号',
      })
    }
    // 1.0 判断手机号不能为空
    // 1.1 显示倒计时
    showCountDown.value = true
    const res = await getCodeAPI({
      mobile: formData.value.mobile,
      type: 'login',
    })
    formData.value.code = res.code
  }

  const formRef = ref<UniHelper.UniFormsInstance>()

  const formRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '请填写手机号码' },
        { pattern: /^1\d{10}$/, errorMessage: '手机号码格式不正确' },
      ],
    },
    code: {
      rules: [
        { required: true, errorMessage: '请输入验证码' },
        { pattern: /^\d{6}$/, errorMessage: '验证码格式不正确' },
      ],
    },
  }

  const isAgree = ref(false)

  const store = useUserStore()
  const onSubmit = async () => {
    await formRef.value!.validate!()
    if (!isAgree.value) {
      uni.showToast({
        title: '请同意协议',
      })
      return
    }
    const res = await loginByMobileApi(formData.value)

    store.token = res.token
    uni.showToast({ title: '登录成功', icon: 'success' })

    uni.switchTab({
      url: '/pages/index/index',
    })
  }
</script>

<template>
  <uni-forms class="login-form" ref="formRef" :model="formData" :rules="formRules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        v-model="formData.mobile"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>

    <uni-forms-item name="code">
      <uni-easyinput
        :input-border="false"
        v-model="formData.code"
        :clearable="false"
        placeholder="请输入验证码"
        placeholder-style="color: #C3C3C5"
      />
      <text class="text-button" v-if="!showCountDown" @click="onShowCountDown">获取验证码</text>
      <view class="text-button" v-else>
        <uni-countdown
          :show-day="false"
          :showHour="false"
          :showMinute="false"
          :second="59"
          color="#16c2a3"
          @timeup="showCountDown = false"
        >
        </uni-countdown>
        秒后获取
      </view>
    </uni-forms-item>

    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit">登 录</button>
  </uni-forms>
</template>

<style lang="scss">
  @import './styles.scss';
</style>
